package cn.agiledata.bank.linkbank.impl.hxb;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.linkbank.exception.LinkBankException;
import cn.agiledata.bank.linkbank.impl.AbstractBankPayResponse;
import cn.agiledata.bank.linkbank.logic.DigitalSignValidatable;

public class HxbNetPayResponse extends AbstractBankPayResponse
implements DigitalSignValidatable {
	private static final String[] RESPONSE_KEYS = { 
		HxbNetConstant.ORDER_NO,	//订单号
		HxbNetConstant.MERCHANT_ID, //商家号
		HxbNetConstant.TX_AMT,		//交易金额
		HxbNetConstant.TX_DATE,		//交易日期
		HxbNetConstant.TX_TIME,		//交易时间
		HxbNetConstant.BILL_STATUS	//订单状态
	};
	
	private String iniFilePath;

	public String getIniFilePath() {
		return iniFilePath;
	}

	public void setIniFilePath(String iniFilePath) {
		this.iniFilePath = iniFilePath;
	}
	
	protected AbstractBankPayResponse getCopiedInstance() {
		HxbNetPayResponse response = new HxbNetPayResponse();
		response.iniFilePath = this.iniFilePath;
		return response;
	}
	/**
	 * 商户号
	 * @return
	 */
	public String getMerchantId() { // 商户号
		return this.getMessage(HxbNetConstant.MERCHANT_ID);
	}
	/**
	 * 交易金额
	 * @return 
	 */
	public BigDecimal getAmount() {// 交易金额
		try {
			return new BigDecimal(renderAmount(this.getMessage(HxbNetConstant.TX_AMT)));
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 构造缩小１００倍的金额
	 * @param amount
	 * @return
	 */
	public String renderAmount(String amount) {
		if(amount == null) {
			return "0";
		}
		if(amount.length()==0) {
			return "0";
		}
		return amount.substring(0, amount.length()-3)+"."+amount.substring(amount.length()-3,amount.length()-1);
	}
	/**
	 * 得到日期
	 */
	public Date getDate() {// 交易日期和时间
		String dateValue = getMessage(HxbNetConstant.TX_DATE);
		String timeValue = getMessage(HxbNetConstant.TX_TIME);
		return DateUtil.string2Date(dateValue + " " + timeValue,
				HxbNetConstant.TX_DATE_RESPONSE_FORMAT + " "
						+ HxbNetConstant.TX_TIME_RESPONSE_FORMAT);
	}
	/**
	 * 成功的返回码
	 */
	public String getSuccessReturnCode() {
		return getMessage(HxbNetConstant.BILL_STATUS);
	}
	/**
	 * 
	 */
	public String getDigitalSign() {
		return this.getMessage(HxbNetConstant.TRANS_RESULT);
	}
	
	public boolean validateDigitalSign(String cryptoKey) throws LinkBankException {
		String[] keys = RESPONSE_KEYS;
		Map values = HxbUtils.parseDigitalSign(getDigitalSign(), keys, cryptoKey, this.iniFilePath);
		this.setMessages(values);
		return true;
	}
	
	public String getCryptoKeyDescription() {
		return null;
	}

	public boolean validateCryptoKey(String cryptoKey) {
		return true;
	}
	/**
	 * 订单状态
	 */
	public String getReturnCode() {// 订单状态
		return getMessage(HxbNetConstant.BILL_STATUS);
	}
	/**
	 * 定单号
	 */
	public String getOrderId() {// 定单号
		return this.getMessage(HxbNetConstant.ORDER_NO);
	}
}
